import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router/index.js'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    username:{
      id: 0,
      username: '',
      password: '',
      nickname: '',
      headUrl: '', // 修改为字符串
      description: '', // 修改为字符串
      status: 1,
      createTime: null,
      updateTime: null,
      isDeleted: 0,
      headpicture: '', // 修改为字符串
      level: null, // 修改为 null
      levellimit: null, // 修改为 null
      smoney: null // 修改为 null


    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER: (state, username) => {
    state.username = username
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        debugger
        this.user=response.data.user
        const { data } = response
        commit('SET_TOKEN', data.token)
        // 打印 data.user 的每个属性及其类型
        // for (const key in data.user) {
        //   if (data.user.hasOwnProperty(key)) {
        //     const value = data.user[key];
        //     console.log(`${key}:`, typeof value, value);
        //   }
        // }
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { name, avatar ,username} = data
        console.log("data",data);
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_USER',username)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()

    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

